#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "dlist.h"

DList* create_list(size_t size)
{
	if(size<10)
		size = 10;
	int i=0;
	DList *plist = (DList*)malloc(sizeof(DList));
#ifdef _DEBUG
	printf("%s\n","create list");
#endif
	if(plist==NULL)
		return NULL;
	
	plist->size = size;
	plist->head = (Node*)malloc(sizeof(Node));
	if(plist->head==NULL)
	{
		free(plist);
		return NULL;
	}

#ifdef _DEBUG
	printf("%s\n","create first node");
#endif
	Node* swp = plist->head;
	swp->i = i;
	swp->next = swp->prev = NULL;

	for(i=1;i<size;i++)
	{
		Node* tmp = (Node*)malloc(sizeof(Node));
		memset((void*)tmp, 0x00, sizeof(Node));
		if(tmp==NULL)
		{
			Node* del = plist->head;
			while(1)
			{
				Node* t = del->next;
				free(del);
				del = t;
				if(del==NULL)
				{
					free(plist);
					return NULL;
				}
			}
		}
		tmp->i = i;
		swp->next = tmp;
		tmp->prev = swp;

#ifdef _DEBUG
	printf("%s\n","create node");
#endif
		swp = tmp;

	}

	plist->head->prev = swp;
	swp->next = plist->head;

	return plist;
}

void destory_list(DList *plist)
{
	if(plist==NULL)
		return;

	Node *del = plist->head->next;
	while(1)
	{
		Node *tmp = del->next;
#ifdef _DEBUG
	printf("free node:%d\n",del->i);
#endif
		free(del);
		del = tmp;
		if(del==plist->head)
		{
#ifdef _DEBUG
				printf("free node:%d\n",del->i);
				printf("free list\n");
#endif
			free(del);
			free(plist);
			return;
		}
	}
}

DList* reverse(DList *plist)
{
	Node * povit = plist->head;
	Node * tmp = NULL;
	
	while(1)
	{
		if(tmp==plist->head)
			break;		
		tmp = povit->next;
		povit->next = povit->prev;
		povit->prev = tmp;
		povit = tmp;		
	}	
	return plist;
}

void traverse(DList *plist)
{
	if(plist==NULL||plist->head==NULL)
		return;

#ifdef _DEBUG
		printf("%s\n","traverse start");
#endif

	Node* tmp = plist->head;
	Node* next = NULL;
	while(1)
	{
		next = tmp->next;
		getchar();
		printf("num:%d\n", tmp->i);

		if(next==plist->head)
			break;
		tmp = next;
	}	
}

